﻿using FB.Data.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Web.Mvc;

namespace FB.Helpers
{
    public static class EnumHelper
    {

        public static List<EnumValuePair> GetKeyValues<E>()
        {
            var r = new List<EnumValuePair>();
            var values = Enum.GetValues(typeof(E));
            foreach (dynamic e in values)
            {
                r.Add(new EnumValuePair { ID = (long)e, Name = e.ToString(), Desc = FB.Helpers.EnumHelper.GetDescription(e) });
            }
            return r;
        }

        /// <summary>
        /// Retrieve the description on the enum, e.g.
        /// [Description("Bright Pink")]
        /// BrightPink = 2,
        /// Then when you pass in the enum, it will retrieve the description
        /// </summary>
        /// <param name="en">The Enumeration</param>
        /// <returns>A string representing the friendly name</returns>
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                // get the Localized DescriptionAttribute
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(FB.Annotations.LocalizedDescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {

                    return ((FB.Annotations.LocalizedDescriptionAttribute)attrs[0]).Description;
                }
                else
                {
                    // get the DescriptionAttribute
                    attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (attrs != null && attrs.Length > 0)
                    {
                        return ((DescriptionAttribute)attrs[0]).Description;
                    }
                }
            }

            return en.ToString();
        }

        public static List<SelectListItem> EnumToSelectListItem<E>()
        {
            Type EnumType = typeof(E);
            return EnumToSelectListItem(EnumType);
        }

        public static List<SelectListItem> EnumToSelectListItem(Type EnumType)
        {
            var items = new List<SelectListItem>();
            //Type EnumType = typeof(E);

            if (EnumType.IsEnum)
            {
                var enums = Enum.GetNames(EnumType);
                if (null != enums)
                {
                    foreach (var e in enums)
                    {
                        var en = Enum.Parse(EnumType, e);
                        items.Add(new SelectListItem { Text = EnumHelper.GetDescription(en as Enum), Value = en.ToString() });
                    }
                }
            }

            return items;
        }


    }
}
